import {
  WeiboOutlined,
  LockOutlined,
  MobileOutlined,
  AlipayOutlined,
  UserOutlined,
  TaobaoOutlined,
} from '@ant-design/icons';
import { Alert, message, Tabs, Divider, Space } from 'antd';
import React, { useState } from 'react';
import { ProFormCaptcha, ProFormCheckbox, ProFormText, LoginForm } from '@ant-design/pro-form';
import { useIntl, history, FormattedMessage, SelectLang, useModel } from 'umi';
// import { login } from '@/services/ant-design-pro/api';
import { getFakeCaptcha } from '@/services/ant-design-pro/login';
import loginIcon from '@/assets/img/login_icon.svg';
import { login } from '@/services/api/login';
import { setToken } from '@/utils/auth';

import styles from './index.less';

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
);
const iconStyles = {
  color: 'rgba(0, 0, 0, 0.2)',
  fontSize: '18px',
  verticalAlign: 'middle',
  cursor: 'pointer',
};
const Login: React.FC = () => {
  const [userLoginState] = useState<API.LoginResult>({});
  const [type, setType] = useState<string>('account');
  const { initialState, setInitialState } = useModel('@@initialState');

  const intl = useIntl();
  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    console.log(userInfo);
    if (userInfo) {
      await setInitialState((s: any) => ({
        ...s,
        currentUser: userInfo,
      }));
    }
  };

  // 处理提交
  const handleSubmit = async (values: API.LoginParams) => {
    return login(values)
      .then(async (res) => {
        console.log(res);
        const { msg, data }: any = res;
        // TOKEN 放入cookie
        setToken(data);
        message.success(msg);
        await fetchUserInfo();
        if (!history) return Promise.resolve(true);
        /** 此方法会跳转到 redirect 参数所在的位置 */
        const { query } = history.location;
        const { redirect } = query as { redirect: string };
        history.push(redirect || '/');
        return Promise.resolve(true);
      })
      .catch(() => {
        return Promise.reject(false);
      });
  };
  const { status, type: loginType } = userLoginState;

  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <div className={styles.left}>
          <div className={styles.leftBox}>
            <div className={styles.logoContainer}>logo</div>
            <div className={styles.iconContainer}>
              <img className={styles.loginIcon} src={loginIcon} />
              <div className={styles.text}>
                <h1 className={styles.title}>Gollum Micro Service</h1>
                <p className={styles.desc}>开源中台系统</p>
              </div>
            </div>
          </div>
        </div>
        <div className={styles.right}>
          <div className={styles.lang} data-lang>
            {SelectLang && <SelectLang />}
          </div>
          <div className={styles.loginForm}>
            <h1 className={styles.title}>Gollum Micro Service</h1>
            <div>
              <LoginForm
                initialValues={{
                  autoLogin: true,
                }}
                style={{ width: '440px' }}
                // actions={[
                //   <FormattedMessage
                //     key="loginWith"
                //     id="pages.login.loginWith"
                //     defaultMessage="其他登录方式"
                //   />,
                //   <AlipayCircleOutlined key="AlipayCircleOutlined" className={styles.icon} />,
                //   <TaobaoCircleOutlined key="TaobaoCircleOutlined" className={styles.icon} />,
                //   <WeiboCircleOutlined key="WeiboCircleOutlined" className={styles.icon} />,
                // ]}
                onFinish={async (values) => {
                  await handleSubmit(values as API.LoginParams);
                  return true;
                }}
              >
                <Tabs size={'large'} activeKey={type} onChange={setType}>
                  <Tabs.TabPane
                    key="account"
                    tab={intl.formatMessage({
                      id: 'pages.login.accountLogin.tab',
                      defaultMessage: '账户密码登录',
                    })}
                  />
                  <Tabs.TabPane
                    key="mobile"
                    tab={intl.formatMessage({
                      id: 'pages.login.phoneLogin.tab',
                      defaultMessage: '手机号登录',
                    })}
                  />
                </Tabs>
                {status === 'error' && loginType === 'account' && (
                  <LoginMessage
                    content={intl.formatMessage({
                      id: 'pages.login.accountLogin.errorMessage',
                      defaultMessage: '账户或密码错误(admin/ant.design)',
                    })}
                  />
                )}
                {type === 'account' && (
                  <>
                    <ProFormText
                      name="username"
                      initialValue="Herther"
                      fieldProps={{
                        size: 'large',
                        prefix: <UserOutlined className={styles.prefixIcon} />,
                      }}
                      placeholder={intl.formatMessage({
                        id: 'pages.login.username.placeholder',
                        defaultMessage: '用户名: admin or user',
                      })}
                      rules={[
                        {
                          required: true,
                          message: (
                            <FormattedMessage
                              id="pages.login.username.required"
                              defaultMessage="请输入用户名!"
                            />
                          ),
                        },
                      ]}
                    />
                    <ProFormText.Password
                      name="password"
                      initialValue="admin123"
                      fieldProps={{
                        size: 'large',
                        prefix: <LockOutlined className={styles.prefixIcon} />,
                      }}
                      placeholder={intl.formatMessage({
                        id: 'pages.login.password.placeholder',
                        defaultMessage: '密码: ant.design',
                      })}
                      rules={[
                        {
                          required: true,
                          message: (
                            <FormattedMessage
                              id="pages.login.password.required"
                              defaultMessage="请输入密码！"
                            />
                          ),
                        },
                      ]}
                    />
                  </>
                )}
                {status === 'error' && loginType === 'mobile' && (
                  <LoginMessage content="验证码错误" />
                )}
                {type === 'mobile' && (
                  <>
                    <ProFormText
                      fieldProps={{
                        size: 'large',
                        prefix: <MobileOutlined className={styles.prefixIcon} />,
                      }}
                      name="mobile"
                      placeholder={intl.formatMessage({
                        id: 'pages.login.phoneNumber.placeholder',
                        defaultMessage: '手机号',
                      })}
                      rules={[
                        {
                          required: true,
                          message: (
                            <FormattedMessage
                              id="pages.login.phoneNumber.required"
                              defaultMessage="请输入手机号！"
                            />
                          ),
                        },
                        {
                          pattern: /^1\d{10}$/,
                          message: (
                            <FormattedMessage
                              id="pages.login.phoneNumber.invalid"
                              defaultMessage="手机号格式错误！"
                            />
                          ),
                        },
                      ]}
                    />
                    <ProFormCaptcha
                      fieldProps={{
                        size: 'large',
                        prefix: <LockOutlined className={styles.prefixIcon} />,
                      }}
                      captchaProps={{
                        size: 'large',
                      }}
                      placeholder={intl.formatMessage({
                        id: 'pages.login.captcha.placeholder',
                        defaultMessage: '请输入验证码',
                      })}
                      captchaTextRender={(timing, count) => {
                        if (timing) {
                          return `${count} ${intl.formatMessage({
                            id: 'pages.getCaptchaSecondText',
                            defaultMessage: '获取验证码',
                          })}`;
                        }
                        return intl.formatMessage({
                          id: 'pages.login.phoneLogin.getVerificationCode',
                          defaultMessage: '获取验证码',
                        });
                      }}
                      name="captcha"
                      rules={[
                        {
                          required: true,
                          message: (
                            <FormattedMessage
                              id="pages.login.captcha.required"
                              defaultMessage="请输入验证码！"
                            />
                          ),
                        },
                      ]}
                      onGetCaptcha={async (phone) => {
                        const result = await getFakeCaptcha({
                          phone,
                        });
                        if (result === false) {
                          return;
                        }
                        message.success('获取验证码成功！验证码为：1234');
                      }}
                    />
                  </>
                )}
                <div
                  style={{
                    marginBlockEnd: 24,
                  }}
                >
                  <ProFormCheckbox noStyle name="autoLogin">
                    自动登录
                  </ProFormCheckbox>
                  <a
                    style={{
                      float: 'right',
                    }}
                  >
                    忘记密码
                  </a>
                </div>
              </LoginForm>
            </div>
            <div>
              <Divider plain>
                <span style={{ color: '#CCC', fontWeight: 'normal', fontSize: 14 }}>
                  其他登录方式
                </span>
              </Divider>
              <Space>
                <Space align="center" size={24}>
                  <div
                    style={{
                      display: 'flex',
                      justifyContent: 'center',
                      alignItems: 'center',
                      flexDirection: 'column',
                      height: 40,
                      width: 40,
                      border: '1px solid #D4D8DD',
                      borderRadius: '50%',
                    }}
                  >
                    <AlipayOutlined style={{ ...iconStyles, color: '#1677FF' }} />
                  </div>
                  <div
                    style={{
                      display: 'flex',
                      justifyContent: 'center',
                      alignItems: 'center',
                      flexDirection: 'column',
                      height: 40,
                      width: 40,
                      border: '1px solid #D4D8DD',
                      borderRadius: '50%',
                    }}
                  >
                    <TaobaoOutlined style={{ ...iconStyles, color: '#FF6A10' }} />
                  </div>
                  <div
                    style={{
                      display: 'flex',
                      justifyContent: 'center',
                      alignItems: 'center',
                      flexDirection: 'column',
                      height: 40,
                      width: 40,
                      border: '1px solid #D4D8DD',
                      borderRadius: '50%',
                    }}
                  >
                    <WeiboOutlined style={{ ...iconStyles, color: '#333333' }} />
                  </div>
                </Space>
              </Space>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};
export default Login;
